package py.patch.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

import org.apache.log4j.Logger;

public class ReadUtil {

	public static Logger logger = Logger.getLogger(ReadUtil.class);

	public static void main(String[] args) throws Exception {
		copyFile("e:/exportTemp.xls","e:"+File.separator+"jjj.xls");
	}

	/**
	 * 以行为单位读取文件，常用于读面向行的格式化文件
	 */
	public static Map<Integer, String> readFileByLines(String fileName) {

		Map<Integer, String> map = new HashMap<Integer, String>();
		fileName = ReadUtil.class.getResource("/").getPath() + File.separator
				+ fileName;

		File file = new File(fileName);
		BufferedReader reader = null;
		try {
			logger.debug(String.format("读取文件:", fileName));
			reader = new BufferedReader(new FileReader(file));
			String tempString = null;
			int line = 1;
			// 一次读入一行，直到读入null为文件结束
			while ((tempString = reader.readLine()) != null) {
				// 显示行号
				logger.debug(String.format("line[%s]:%s ", line, tempString));
				map.put(line, tempString);
				line++;
			}
			reader.close();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e1) {
				}
			}
		}

		return map;
	}

	public static void copyFile(String srcPath, String destPath) throws Exception {
		int lastSlash = destPath.lastIndexOf(File.separator);
		String dirdestPath = destPath.substring(0,lastSlash);
		
		File dirdest = new File(dirdestPath);
		if(!dirdest.exists()){
			dirdest.mkdirs();
		}
		
		File srcFile = new File(srcPath);
		if(!srcFile.exists()){
			throw new RuntimeException(srcPath+":不存在");
		}
		File destFile = new File(destPath);
		
		ReadUtil.copyFile(srcFile,destFile);
		destFile.setLastModified(srcFile.lastModified());
	}
	
	public static void copyFile(File src, File dest) throws Exception {
		BufferedInputStream reader = null;
		BufferedOutputStream writer = null;
		try {
			reader = new BufferedInputStream(new FileInputStream(src));
			writer = new BufferedOutputStream(new FileOutputStream(dest));
			byte[] buff = new byte[reader.available()];
			while ((reader.read(buff)) != -1) {
				writer.write(buff);
			}
		} catch (Exception e) {
			logger.error(e);
		} finally {
			writer.flush();
			writer.close();
			reader.close();
		}
	}
	
	/**
     * 删除空目录
     * @param dir 将要删除的目录路径
     */
    public static void doDeleteEmptyDir(String dir) {
        boolean success = (new File(dir)).delete();
        if (success) {
            System.out.println("Successfully deleted empty directory: " + dir);
        } else {
            System.out.println("Failed to delete empty directory: " + dir);
        }
    }

    /**
     * 递归删除目录下的所有文件及子目录下所有文件
     * @param dir 将要删除的文件目录
     * @return boolean Returns "true" if all deletions were successful.
     *                 If a deletion fails, the method stops attempting to
     *                 delete and returns "false".
     */
    public static boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            //递归删除目录中的子目录下
            for (int i=0; i<children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        // 目录此时为空，可以删除
        return dir.delete();
    }
    
    
	public static Map<String,Object> getFileMap(File f,Map<String,Object> map){
		if(map ==null){
			map = new HashMap<String,Object>();
		}
	    if(f!=null){
	        if(f.isDirectory()){
	            File[] fileArray=f.listFiles();
	            if(fileArray!=null){
	                for (int i = 0; i < fileArray.length; i++) {
	                	
	                    //递归调用
	                	getFileMap(fileArray[i],map);
	                }
	            }
	        }
	        else{
	        	logger.debug("读取文件:"+f.getAbsolutePath());
	            map.put(map.size()+1+"", f);
	        }
	    }
	    return SortUtil.sortMapByKey(map);
	}

	
}
